﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text;
using XieCan.Core.Swigger.filters;

namespace XieCan.Core.Swigger
{
  public static class SwaggerExtension
  {
    public static IServiceCollection AddSwaggerExt(this IServiceCollection services, ConfigurationManager Configuration)
    {
      services.AddEndpointsApiExplorer();

      #region 添加JWT验证
      services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
      {
        options.TokenValidationParameters = new TokenValidationParameters()
        {
          ValidateIssuer = true,
          ValidIssuer = Configuration["JWT:Issuer"],

          ValidateAudience = true,
          ValidAudience = Configuration["JWT:Audience"],

          ValidateLifetime = true,
          IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["JWT:SecretKey"]))
        };
      });
      #endregion

      services.AddSwaggerGen(option =>
      {
        #region 显示注释
        {
          option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, $"{AppDomain.CurrentDomain.FriendlyName}.xml"), true);
          //option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "XieCan.Core.Model.xml"), true);
          option.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, "XieCan.Core.DTO.xml"), true);
          option.OrderActionsBy(api => api.HttpMethod);
        }
        #endregion

        #region 多版本控制
        {
          foreach (var version in Enum.GetNames(typeof(ApiVersion)))
          {
            option.SwaggerDoc(version, new OpenApiInfo
            {
              Version = version,
              Title = $"后台管理系统在线接口文档",
              Description = $"版本:{version}",
              Contact = new OpenApiContact
              {
                Name = "谢灿软件工作室",
                Email = "492384481@qq.com",
                Url = new Uri("https://www.xiecan.cc")
              }
            });
          }

        }
        #endregion

        #region JWT鉴权
        option.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
        {
          Description = "请输入token，格式为：Bearer token",
          Name = "Authorization",
          In = ParameterLocation.Header,
          Type = SecuritySchemeType.ApiKey,
          BearerFormat = "JWT",
          Scheme = "Bearer"
        });

        //注册全局认证（所有的接口都可以使用认证）
        option.AddSecurityRequirement(new OpenApiSecurityRequirement {
            {
              new OpenApiSecurityScheme
              {
                Reference = new OpenApiReference
                {
                  Type = ReferenceType.SecurityScheme,
                  Id = "Bearer"
                }
              }, Array.Empty<string>()
            }
          });
        #endregion

        #region        
        option.SchemaFilter<SchemaFilter>();
        #endregion

        //option.OperationFilter<FileUploadFilter>();
      });

      return services;
    }

    public static IApplicationBuilder UseSwaggerExt(this IApplicationBuilder app)
    {
      app.UseAuthentication();

      app.UseSwagger().UseSwaggerUI(option =>
      {
        // 显示多版本
        foreach (var version in Enum.GetNames(typeof(ApiVersion)))
        {
          option.SwaggerEndpoint($"/swagger/{version}/swagger.json", $"后台管理系统 {version}");
        }
      });
      return app;
    }
  }
}
